from flask import Blueprint, render_template, request
from apps.pojo.Entity import User,UserSchema,db
from apps.util.LayData import LayData

user_bp = Blueprint('user', __name__, url_prefix='/user')
user_schema = UserSchema(many=True)

@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')

@user_bp.route('/list')
def list():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    offset = (page - 1) * limit
    # 查询用户列表
    userList = User.query.offset(offset).limit(limit).all()
    users = user_schema.dump(userList)
    # 查询数据库记录数
    count = User.query.count()
    # 拼凑layui要求的数据格式
    data = LayData.data(0, '查询成功', count, users)

    return data


@user_bp.route('/toadd')
def toAdd():
    return render_template('user/add.html')


@user_bp.route('/addSave', methods=['POST'])
def addSave():
    username = request.form.get('username')
    password = request.form.get('password')
    user = User()
    user.username = username
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
        return LayData.data2(0, '添加成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '添加失败')


@user_bp.route('/toupdate/<int:id>')
def toUpdate(id):
    user = User.query.get(id)
    return render_template('user/update.html', user=user)


@user_bp.route('/updateSave', methods=['POST'])
def updateSave():
    id = request.form.get('id')
    username = request.form.get('username')
    password = request.form.get('password')

    user = User.query.get(id)
    user.username = username
    user.password = password
    try:
        db.session.commit()
        return LayData.data2(0, '更新成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '更新失败')


@user_bp.route('/delete/<int:id>', methods=['GET'])
def delete(id):
    user = User.query.get(id)
    try:
        db.session.delete(user)
        db.session.commit()
        return LayData.data2(0, '删除成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '删除失败')
